package com.sunsy.authserver.filter;

import com.sunsy.authserver.enums.ErrorCode;
import com.sunsy.authserver.util.JwtUtil;
import com.sunsy.authserver.util.Tools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author sunsiyuan
 * 判断用户是否登陆的，如果没有登陆，强制跳转到登陆接口
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
@Order(1)
public class LoginFilter implements Filter {

    private JwtUtil jwtUtil;

    @Autowired
    public void setJwtUtil(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    /**
     * 不过滤的资源
     */
    @Value("${zuul.white_url}")
    private ArrayList nofilter;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        log.info("current  url  is {}", request.getServletPath());
        boolean flag = Tools.isNofilter(request,nofilter);
        if (flag) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String access_token = request.getHeader("Authorization");
        access_token = StringUtils.isBlank(access_token) ? request.getParameter("access_token") : access_token;
        if (StringUtils.isBlank(access_token) || !jwtUtil.verify(access_token)) {
            ErrorCode.ACCESS_TOKEN_PARAMS.apiExc();
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }



}
